﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EffiProz.Core.Lib
{
    public class OrderedHashSet : HashSet, EfzList
    {
        public OrderedHashSet()
            : base(8)
        {
            isList = true;
        }

        public override bool remove(Object key)
        {

            int oldSize = size();

            base.removeObject(key, true);

            return oldSize != size();
        }

        public Object remove(int index)
        {

            checkRange(index);

            Object result = objectKeyTable[index];

            remove(result);

            return result;
        }

        public bool insert(int index,
                              Object key)
        {

            if (index < 0 || index > size())
            {
                throw new IndexOutOfRangeException();
            }

            if (contains(key))
            {
                return false;
            }

            if (index == size())
            {
                return add(key);
            }

            Object[] set = toArray(new Object[size()]);

            base.clear();

            for (int i = 0; i < index; i++)
            {
                add(set[i]);
            }

            add(key);

            for (int i = index; i < set.Length; i++)
            {
                add(set[i]);
            }

            return true;
        }

        public Object set(int index, Object key)
        {
            throw new IndexOutOfRangeException();
        }

        public void add(int index, Object key)
        {
            throw new IndexOutOfRangeException();
        }

        public Object get(int index)
        {

            checkRange(index);

            return objectKeyTable[index];
        }

        public int getIndex(Object key)
        {
            return getLookup(key, key.GetHashCode());
        }

        public int getLargestIndex(OrderedHashSet other)
        {

            int max = -1;

            for (int i = 0, size = other.size(); i < size; i++)
            {
                int index = getIndex(other.get(i));

                if (index > max)
                {
                    max = index;
                }
            }

            return max;
        }

        private void checkRange(int i)
        {

            if (i < 0 || i >= size())
            {
                throw new IndexOutOfRangeException();
            }
        }
    }
}
